//
//  YZCreateNoteVC.m
//  VET
//
//  Created by 刘文靖 on 2018/7/10.
//  Copyright © 2018年 YZ. All rights reserved.
//

#import "YZCreateNoteVC.h"
#import "YZNoteInputView.h"
#import "YZWorkNoteModel.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#import "TZImagePickerController.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "UIViewController+YZImagePicker.h"
#import "YZLineView.h"
#import "YZArchieveVC.h"
#import "YZPublishWorkNoteManage.h"
#import "YZNetworkManager.h"
#import "MJExtension.h"
#import "YZRouter+AutoVC.h"
#import "YZAudioRecordVC.h"
#import "YZRecordManager.h"
#import "YZAutoRowModel.h"
#import "YZPigModel.h"
#import "YZSwineryModel.h"
#import "NSDate+YZDatePickView.h"
#import "YZCameraVC.h"
#import "YZVideoVC.h"
@interface YZCreateNoteVC ()<UIScrollViewDelegate,TZImagePickerControllerDelegate,YZNoteInputViewDelegate,YZMediaProtocol>
@property (strong, nonatomic) UIScrollView *mainScrollView;
@property (strong, nonatomic) YZNoteInputView *inputView;
@property (nonatomic, strong) NSMutableArray *selectedPhotos;
@property (nonatomic, strong) NSMutableArray *selectedAssets;

@property (nonatomic, strong) NSMutableDictionary *noteDic;
@property (nonatomic, weak) UIButton *rightButton;
@property (nonatomic, assign) BOOL isSelectOriginalPhoto;
@property (nonatomic, strong) NSString *mediaPath;
@property (nonatomic, strong) UILabel *categoryLabel;
@property (nonatomic, strong) UILabel *archieveLabel;
@property (nonatomic, strong) UISwitch *taskSwitch;
@property (nonatomic, strong) YZAutoRowModel *selectedCategoryItem;
@property (nonatomic, strong) NSArray *selectedArchieveList;
@property (nonatomic, assign) NSInteger audioMediaTime;
@property (nonatomic, strong) NSString *mediaOrientation;

@end

@implementation YZCreateNoteVC

- (void)viewDidLoad {
    [super viewDidLoad];
    _selectedPhotos = [NSMutableArray array];
    _selectedAssets = [NSMutableArray array];
    self.selectedArchieveList = self.note.archiveList?:self.archiveList;
    [self setupNavigationBar];
    [self setupMainView];
}

- (void)setupNavigationBar{
    self.title = @"创建笔记";
    UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 36, 25)];
    [rightButton setTitle:@"保存" forState:UIControlStateNormal];
    [rightButton setTitleColor:kColorWithHex(0x32BE60) forState:UIControlStateNormal];
    [rightButton setTitleColor:kColorWithHex(0xcecece) forState:UIControlStateDisabled];
    rightButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:18];
    [rightButton addTarget:self action:@selector(saveNote) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *righBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = righBarButtonItem;
    self.rightButton = rightButton;
}

- (void)setupMainView{
    self.mainScrollView = [[UIScrollView alloc] initWithFrame:self.view.frame];
    self.mainScrollView.backgroundColor  = kColorWithHex(0xffffff);
    self.mainScrollView.delegate = self;
    self.mainScrollView.alwaysBounceVertical = YES;
    self.mainScrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.mainScrollView];
    self.inputView = [[YZNoteInputView alloc] init];
    self.inputView.placeHolder = @"点击输入笔记内容…";
    self.inputView.delegate = self;
    [self.mainScrollView addSubview:self.inputView];
    [self.inputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.offset(0);
        make.height.mas_equalTo(self.note?426:384);
    }];
    
    UIButton *createTimeBtn;
    if (self.note){
        self.inputView.note = self.note;
        createTimeBtn = [self createButtonWithTitle:@"记录时间" subTitle:nil imageName:@"ico_type" topMargin:20 needOperation:NO];
        [createTimeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.inputView.mas_bottom).offset(10);
            make.left.right.offset(0);
            make.size.mas_equalTo(CGSizeMake(kScreenWidth, 0));
        }];
        
        UILabel *createTimeLabel = [[UILabel alloc] init];
        createTimeLabel.textColor = kColorWithHex(0x434343);
        createTimeLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16];
        createTimeLabel.text = [NSDate yz_getDateStringFromTimeInterval:self.note.createTime format:@"yyyy-MM-dd HH:mm"];
        [createTimeBtn addSubview:createTimeLabel];
        [createTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.offset(0);
            make.right.offset(-47);;
        }];
        if (self.note.noteType) {
            YZAutoRowModel *selectedCategoryItem = [[YZAutoRowModel alloc] init];
            selectedCategoryItem.displayValue = self.note.noteType.itemValue;
            selectedCategoryItem.paramValue = [NSString stringWithFormat:@"%ld",(long)self.note.noteType.itemKey];
            self.selectedCategoryItem = selectedCategoryItem;
        }
        createTimeBtn.hidden = YES;
    }
    
    UIButton *categoryBtn = [self createButtonWithTitle:@"笔记类别" subTitle:nil imageName:@"ico_type_biji" topMargin:15 needOperation:YES];
    [categoryBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(createTimeBtn?createTimeBtn.mas_bottom:self.inputView.mas_bottom);
        make.left.right.offset(0);
        make.size.mas_equalTo(CGSizeMake(kScreenWidth, 54));
    }];
    
    self.categoryLabel = [[UILabel alloc] init];
    self.categoryLabel.textColor = kColorWithHex(0x434343);
    self.categoryLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16];
    [categoryBtn addSubview:self.categoryLabel];
    [self.categoryLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.right.offset(-47);
    }];
    self.categoryLabel.text = self.note.noteType.itemValue?:@"请选择";
    
    UIButton *archieveBtn = [self createButtonWithTitle:@"笔记归档" subTitle:@"笔记归档指为当前笔记选择存储对象" imageName:@"ico_gd_biji" topMargin:9 needOperation:!self.archiveList.count];
    [archieveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(categoryBtn.mas_bottom);
        make.left.right.offset(0);
        make.size.mas_equalTo(CGSizeMake(kScreenWidth, 54));
    }];
    self.archieveLabel = [[UILabel alloc] init];
    self.archieveLabel.textColor = kColorWithHex(0x434343);
    self.archieveLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16];
    [archieveBtn addSubview:self.archieveLabel];
    [self.archieveLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.right.offset(-47);
        make.left.mas_greaterThanOrEqualTo(138);
    }];
    if (self.archiveList.count) {
        YZArchiveModel *archive = self.archiveList.firstObject;
        self.archieveLabel.text = [NSString stringWithFormat:@"%@",archive.archiveStr];
    }else{
        self.archieveLabel.text = self.selectedArchieveList.count?[NSString stringWithFormat:@"%lu个对象",(unsigned long)self.selectedArchieveList.count]:@"请选择";
    }
    UIButton *syncBtn = [self createButtonWithTitle:@"同步创建待办任务" subTitle:@"如果开启，则会在第二天产生一个待办任务" imageName:@"ico_renwu_biji" topMargin:23 needOperation:NO];
    [syncBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(archieveBtn.mas_bottom);
        make.left.right.offset(0);
        make.size.mas_equalTo(CGSizeMake(kScreenWidth, 78));
        make.bottom.offset(-80);
    }];
    syncBtn.userInteractionEnabled = YES;
    self.taskSwitch = [[UISwitch alloc] init];
    [syncBtn addSubview:self.taskSwitch];
    [self.taskSwitch mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(51, 31));
        make.right.offset(-23);
        make.centerY.offset(0);
    }];
    
    [categoryBtn addTarget:self action:@selector(categoryBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [archieveBtn addTarget:self action:@selector(archieveBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
}

- (UIButton *)createButtonWithTitle:(NSString *)title subTitle:(NSString*)subTitle imageName:(NSString *)imageName topMargin:(CGFloat)topMargin needOperation:(BOOL)operation{
    UIButton *btn= [[UIButton alloc] init];
    btn.backgroundColor = [UIColor whiteColor];
    [self.mainScrollView addSubview:btn];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imageName]];
    imageView.backgroundColor =kColorWithHex(0xf8f8f8);
    [btn addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(24, 24));
        make.left.offset(26);
        make.top.offset(topMargin);
    }];
    
    UILabel *label = [[UILabel alloc] init];
    label.textColor = kColorWithHex(0x393939);;
    label.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16];;
    label.text = title;
    [btn addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(imageView);
        make.height.mas_equalTo(14);
        make.left.mas_equalTo(imageView.mas_right).offset(16);
    }];
    if (subTitle){
        UILabel *subLabel = [[UILabel alloc] init];
        subLabel.textColor = kColorWithHex(0x9B9B9B);
        subLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:12];;
        subLabel.text = subTitle;
        [btn addSubview:subLabel];
        [subLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(label.mas_bottom).offset(8);
            make.left.mas_equalTo(label);
        }];
    }
    if (operation) {
        UIImageView *arrowIV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ico_right"]];
        [btn addSubview:arrowIV];
        [arrowIV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.offset(0);
            make.right.offset(-29);
        }];
    }else{
        btn.userInteractionEnabled = NO;
    }
    
    YZLineView *lineView = [[YZLineView alloc] init];
    [btn addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(.5);
        make.left.offset(24);
        make.centerX.bottom.offset(0);
    }];
    return btn;
}

#pragma mark -clickEvents
- (void)saveNote{
    if (!self.inputView.textView.text.length && !self.mediaPath.length && !self.selectedPhotos.count && !self.note) {
         [SVProgressHUD yz_showMessage:@"请完善选项内容后再保存!"];
        self.rightButton.enabled = YES;
        return;
    }
    [SVProgressHUD show];
    self.noteDic = [NSMutableDictionary dictionary];
    self.noteDic[@"noteText"] = self.inputView.textView.text;
    if (self.selectedCategoryItem) {
        self.noteDic[@"noteType"] = self.selectedCategoryItem.paramValue;
    }
    if (self.taskSwitch.isOn) {
        self.noteDic[@"isCreateTask"] = @(1);
    }
    if (self.selectedArchieveList.count) {
        NSMutableArray *archiveList = [NSMutableArray array];
        for (id archiveModel in self.selectedArchieveList) {
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            dict[@"archiveId"] = @([archiveModel archiveId]);
            dict[@"archiveType"] = [archiveModel archiveType];
            [archiveList addObject:dict];
        }
        self.noteDic[@"archiveList"] = archiveList;
        //self.noteDic[@"isArchived"] = @(1);
    }
    YZPublishWorkNoteManage *publishManage = [YZPublishWorkNoteManage shareManager];
    publishManage.note = self.note;
    NSMutableDictionary *mediaParams = [NSMutableDictionary dictionary];
    if (self.mediaPath) {
        PHAsset *phAsset = self.selectedAssets.firstObject;
        if (phAsset.mediaType == PHAssetMediaTypeVideo) {
           mediaParams[@"mediaType"]  = @"video/mp4";
            mediaParams[@"mediaOrientation"] = self.mediaOrientation;
        }else{
            mediaParams[@"mediaType"]  = @"audio/aac";
            mediaParams[@"mediaTime"] = @(self.audioMediaTime);
        }
    }
    
    [publishManage publishWorkNote:self.noteDic mediaPath:self.mediaPath selectedPhotos:self.selectedPhotos mediaParams:mediaParams completion:^{
        if (self.createNoteSuccessBlock) {
            self.createNoteSuccessBlock();
        }
        [self.navigationController popViewControllerAnimated:YES];
    }];
}

- (void)categoryBtnClick{
    [[YZRouter sharedInstance] yz_atuoPush:@"note_type_VC" params:nil itemClick:^(YZAutoRowModel *item) {
        self.selectedCategoryItem = item;
        self.categoryLabel.text = item.displayValue;
    }] ;
}

- (void)archieveBtnClick{
    YZArchieveVC *archieveVC = [[YZArchieveVC alloc] init];
    archieveVC.archiveList = [NSMutableArray arrayWithArray:self.selectedArchieveList];
    @weakify(self)
    archieveVC.archieveSuccessBlock = ^(NSArray *selectedArr) {
        @strongify(self)
        self.selectedArchieveList = selectedArr;
        self.archieveLabel.text = self.selectedArchieveList.count?[NSString stringWithFormat:@"%lu个对象",(unsigned long)self.selectedArchieveList.count]:@"请选择";
    };
    
    [self.navigationController pushViewController:archieveVC animated:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}
#pragma mark - YZNoteInputViewDelegate

- (void)audioBtnDidClick:(YZNoteInputView *)view{
    YZAudioRecordVC  *recordVC = [[YZAudioRecordVC alloc] init];
    recordVC.recordSuccessBlock = ^(NSString *recordPath, NSInteger timeInterval) {
        self.mediaPath = recordPath;
        self.audioMediaTime = timeInterval;
       [self.inputView showAudioViewWithAudioUrl:recordPath timeInterval:timeInterval];
    };
    [self presentViewController:recordVC animated:YES completion:nil];
}

- (void)imageBtnDidClick:(YZNoteInputView *)view{
    @weakify(self)
    [self yz_presentSelectSheetWithTitle:nil cancelButtonTitle:nil twoOtherButtonTitlesArray:@[@"从相册选择",@"拍照"] firstSelBTHandler:^{
        @strongify(self)
        [self pushTZImagePickerController:NO];
    } secondSelBTHandler:^{
        @strongify(self)
        YZCameraVC *cameraVC = [YZCameraVC new];
        cameraVC.delegate = self;
        [self presentViewController:cameraVC animated:YES completion:nil];
    }];
}

- (void)videoBtnDidClick:(YZNoteInputView *)view{
    YZVideoVC *videoVC = [YZVideoVC new];
    videoVC.delegate = self;
    [self presentViewController:videoVC animated:YES completion:nil];
}

- (void)audioDeleteDidClick:(YZNoteInputView *)view{
    [[NSFileManager defaultManager] removeItemAtPath:self.mediaPath error:nil];
    self.note.attachmentList = nil;
    self.mediaPath = nil;
    
}

- (void)audioPlayDidClick:(YZNoteInputView *)view{
    [[YZRecordManager shareManager] startPlayRecorder:self.mediaPath];
}

#pragma mark -- YZMediaProtocol

- (void)getCurrentVideoAssert:(PHAsset *)assert andUrl:(NSURL *)url andCurrentOrientation:(AVCaptureVideoOrientation)orientation
{
    if (!assert) return;
    [SVProgressHUD show];
    switch (orientation) {
        case AVCaptureVideoOrientationPortrait:
            self.mediaOrientation = @"top";
            break;
        case AVCaptureVideoOrientationPortraitUpsideDown:
            self.mediaOrientation = @"bottom";
            break;
        case AVCaptureVideoOrientationLandscapeRight:
            self.mediaOrientation = @"right";
            break;
        case AVCaptureVideoOrientationLandscapeLeft:
            self.mediaOrientation = @"left";
            break;
        default:
            self.mediaOrientation = @"top";
            break;
    }
    TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    tzImagePickerVc.sortAscendingByModificationDate = YES;
    [[TZImageManager manager] saveVideoWithUrl:url location:nil completion:^(NSError *error) {
        if (!error) {
            [[TZImageManager manager] getCameraRollAlbum:YES allowPickingImage:NO needFetchAssets:NO completion:^(TZAlbumModel *model) {
                [[TZImageManager manager] getAssetsFromFetchResult:model.result allowPickingVideo:YES allowPickingImage:NO completion:^(NSArray<TZAssetModel *> *models) {
                    TZAssetModel *assetModel = [models firstObject];
                    if (tzImagePickerVc.sortAscendingByModificationDate) {
                        assetModel = [models lastObject];
                    }
                    //视频保存到本地
                    [self getVideoOutputPathWithAsset:assetModel.asset];
                    [[TZImageManager manager] getPhotoWithAsset:assetModel.asset completion:^(UIImage *photo, NSDictionary *info, BOOL isDegraded) {
                        if (!isDegraded && photo) {
                            [self refreshCollectionViewWithAddedAsset:assetModel.asset image:photo];
                        }
                    }];
                }];
            }];
        } else {
            [SVProgressHUD yz_showError:@"获取视频失败"];
        }
    }];
}

- (void)getCurrentPhotoAssert:(PHAsset *)assert
{
    if (!assert) return;
    @weakify(self)
    [[TZImageManager manager] getOriginalPhotoWithAsset:assert completion:^(UIImage *photo, NSDictionary *info) {
        @strongify(self)
        if (photo) {
            [self refreshCollectionViewWithAddedAsset:assert image:photo];
        }
    }];
}

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
- (void)preViewImage:(NSInteger)index{
    id asset;
    if (_selectedAssets.count > index) {
        asset = _selectedAssets[index];
    }else{
        asset = self.inputView.notePics[index];
    }
    BOOL isVideo = self.note.attachType == YZWorkNoteAttachTypeVideo;
    if ([asset isKindOfClass:[PHAsset class]]) {
        PHAsset *phAsset = asset;
        isVideo = phAsset.mediaType == PHAssetMediaTypeVideo;
    }
    else if ([asset isKindOfClass:[ALAsset class]]) {
        ALAsset *alAsset = asset;
        isVideo = [[alAsset valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypeVideo];
    }
    if (isVideo) { // perview video / 预览视频
        NSString *videoUrl = self.mediaPath?:self.note.attachmentList.firstObject.attachmentUrl;
        if (!videoUrl.length) return;
        TZVideoPlayerController *vc = [[TZVideoPlayerController alloc] init];
        vc.videoUrl = videoUrl;
        @weakify(self)
        vc.deleteButtonClickBlock = ^{
           @strongify(self)
            [[NSFileManager defaultManager] removeItemAtPath:self.mediaPath error:nil];
            self.note.attachmentList = nil;
            self.mediaPath = nil;
            [self.selectedPhotos removeAllObjects];
            [self.selectedAssets removeAllObjects];
            self.inputView.selectedPhotos = self.selectedPhotos;
            self.inputView.selectedAssets = self.selectedAssets;
            [self updateInputViewHeightConstraint];
        };
        [self presentViewController:vc animated:YES completion:nil];
    } else{ // preview photos / 预览照片
        NSMutableArray * photoModels = [NSMutableArray arrayWithCapacity:self.inputView.notePics.count];
        for (int i =0 ; i < self.inputView.notePics.count; i++) {
            TZAssetModel *model = [[TZAssetModel alloc] init];
            model.cachedImage = self.inputView.notePics[i];
            [photoModels addObject:model];
        }
        TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithSelectedAssets:_selectedAssets selectedPhotos:self.inputView.notePics photoModels:photoModels index:index];
        imagePickerVc.maxImagesCount = 9;
        imagePickerVc.allowPickingGif = NO;
        imagePickerVc.allowPickingOriginalPhoto = NO;
        imagePickerVc.allowPickingMultipleVideo = NO;
        imagePickerVc.showSelectedIndex = YES;
        imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
        @weakify(self)
        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
            @strongify(self)
//            self.selectedPhotos = [NSMutableArray arrayWithArray:photos];
            self.selectedAssets = [NSMutableArray arrayWithArray:assets];
            self.inputView.selectedPhotos = photos;
            self.inputView.selectedAssets = assets;
            [self updateInputViewHeightConstraint];
        }];
        [imagePickerVc setImagePickerControllerDidDeletedHandle:^(NSInteger index) {
            @strongify(self)
            NSMutableArray *attachmentArr = [NSMutableArray arrayWithArray:self.note.attachmentList];
            if (attachmentArr.count > index) {
                [attachmentArr removeObjectAtIndex:index];
            }else if (self.selectedPhotos.count > index-attachmentArr.count) {
                [self.selectedPhotos removeObjectAtIndex:index-attachmentArr.count];
            }
            self.note.attachmentList = attachmentArr;
        }];
        [self presentViewController:imagePickerVc animated:YES completion:nil];
    }
}


#pragma mark - TZImagePickerController
- (void)pushTZImagePickerController:(BOOL)allowPickingVideo {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9- self.inputView.notePics.count columnNumber:3 delegate:self pushPhotoPickerVc:YES];
    // imagePickerVc.navigationBar.translucent = NO;
    
#pragma mark - 五类个性化设置，这些参数都可以不传，此时会走默认设置
    imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
    
    // 1.设置目前已经选中的图片数组
    //imagePickerVc.selectedAssets = _selectedAssets; // 目前已经选中的图片数组
    imagePickerVc.allowTakePicture = NO; // 在内部显示拍照按钮
    imagePickerVc.allowTakeVideo = NO;   // 在内部显示拍视频按
    imagePickerVc.videoMaximumDuration = 10; // 视频最大拍摄时间
    [imagePickerVc setUiImagePickerControllerSettingBlock:^(UIImagePickerController *imagePickerController) {
        imagePickerController.videoQuality = UIImagePickerControllerQualityTypeHigh;
    }];
    
    imagePickerVc.iconThemeColor = [UIColor colorWithRed:31 / 255.0 green:185 / 255.0 blue:34 / 255.0 alpha:1.0];
    imagePickerVc.showPhotoCannotSelectLayer = YES;
    imagePickerVc.cannotSelectLayerColor = [[UIColor whiteColor] colorWithAlphaComponent:0.8];
//    [imagePickerVc setPhotoPickerPageUIConfigBlock:^(UICollectionView *collectionView, UIView *bottomToolBar, UIButton *previewButton, UIButton *originalPhotoButton, UILabel *originalPhotoLabel, UIButton *doneButton, UIImageView *numberImageView, UILabel *numberLabel, UIView *divideLine) {
//        [doneButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
//    }];
    // 3. 设置是否可以选择视频/图片/原图
    imagePickerVc.allowPickingVideo = allowPickingVideo;
    imagePickerVc.allowPickingImage = !allowPickingVideo;
    imagePickerVc.allowPickingOriginalPhoto = NO;
    imagePickerVc.allowPickingGif = NO;
    imagePickerVc.allowPickingMultipleVideo = NO; // 是否可以多选视频
    
    // 4. 照片排列按修改时间升序
    imagePickerVc.sortAscendingByModificationDate = YES;
    
    imagePickerVc.statusBarStyle = UIStatusBarStyleLightContent;
    
    // 设置是否显示图片序号
    imagePickerVc.showSelectedIndex = YES;
    
#pragma mark - 到这里为止
    
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
    }];
    
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}



#pragma mark - TZImagePickerControllerDelegate

/// User click cancel button
/// 用户点击了取消
- (void)tz_imagePickerControllerDidCancel:(TZImagePickerController *)picker {
    // NSLog(@"cancel");
}

// 这个照片选择器会自己dismiss，当选择器dismiss的时候，会执行下面的代理方法
// 如果isSelectOriginalPhoto为YES，表明用户选择了原图
// 你可以通过一个asset获得原图，通过这个方法：[[TZImageManager manager] getOriginalPhotoWithAsset:completion:]
// photos数组里的UIImage对象，默认是828像素宽，你可以通过设置photoWidth属性的值来改变它
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos {
    [_selectedPhotos addObjectsFromArray:photos];
    [_selectedAssets addObjectsFromArray:assets];
    _isSelectOriginalPhoto = isSelectOriginalPhoto;
    _inputView.selectedPhotos = _selectedPhotos;
    _inputView.selectedAssets = _selectedAssets;
    [self updateInputViewHeightConstraint];
}

// If user picking a video, this callback will be called.
// If system version > iOS8,asset is kind of PHAsset class, else is ALAsset class.
// 如果用户选择了一个视频，下面的handle会被执行
// 如果系统版本大于iOS8，asset是PHAsset类的对象，否则是ALAsset类的对象
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(id)asset {
    [SVProgressHUD show];
    _selectedPhotos = [NSMutableArray arrayWithArray:@[coverImage]];
    _selectedAssets = [NSMutableArray arrayWithArray:@[asset]];
    _inputView.selectedPhotos = _selectedPhotos;
    _inputView.selectedAssets = _selectedAssets;
    [self updateInputViewHeightConstraint];
    //视频保存到本地
    [self getVideoOutputPathWithAsset:asset];
    
    
}

- (void)getVideoOutputPathWithAsset:(id)asset{
    @weakify(self)
    [[TZImageManager manager] getVideoOutputPathWithAsset:asset presetName:AVAssetExportPreset640x480 success:^(NSString *outputPath) {
        @strongify(self)
        self.mediaPath = outputPath;
        [SVProgressHUD dismiss];
    } failure:^(NSString *errorMessage, NSError *error) {
        [SVProgressHUD yz_showError:@"视频获取失败!"];
    }];
}

- (void)refreshCollectionViewWithAddedAsset:(id)asset image:(UIImage *)image{
    [_selectedAssets addObject:asset];
    [_selectedPhotos addObject:image];
    _inputView.selectedPhotos = _selectedPhotos;
    _inputView.selectedAssets = _selectedAssets;
    [self updateInputViewHeightConstraint];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    if ([picker isKindOfClass:[UIImagePickerController class]]) {
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)updateInputViewHeightConstraint{
    [self.inputView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(self.selectedPhotos.count?426:384);
    }];
}
#pragma clang diagnostic pop
@end
